#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -f /etc/os-release ]; then
   echo "Linux system."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   if [ -f ~/.bash_profile ]; then
      source ~/.bash_profile
    fi
elif current_os_is_windows; then
   echo "Windows system."
else
   echo "Unknown OS"
fi

APP_INSTALL_NAME="framepack"
APP_TARGET_DIR_NAME="framepack"

echo "lmdprogress:3"

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/env"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

cd "$CURRENT_APP_PATH"

echo "lmdprogress:8"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

echo "lmdprogress:20"

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/docker_image_util.sh"

gen_image_repo_url $_DOCKER_IMAGE_NAME_LMD $_DOCKER_APP_VERSION
APP_IMAGE_REPO=$APP_IMAGE_REPO_RESULT
echo "docker image repo: "$APP_IMAGE_REPO
docker pull $APP_IMAGE_REPO

echo "lmdprogress:40"

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

if [ -n "$HF_ENDPOINT" ]; then
   export HF_ENDPOINT_PARAM="-e HF_ENDPOINT=$HF_ENDPOINT"
fi

echo "lmdprogress:60"

DOWNLOAD_MODELS_PY_PATH="$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/download_models.py"

export HF_HOME="$CURRENT_APP_PATH/hf_download"
echo "set HF_HOME: "$HF_HOME

echo "start download models"

echo "lmdprogress:75"

if current_os_is_windows; then
   export MSYS_NO_PATHCONV=1 
fi

CONTAINER_NAME="framepack-download-models-temp"

docker stop $CONTAINER_NAME 2>/dev/null
docker rm $CONTAINER_NAME 2>/dev/null

cleanup() {
  echo "clean container"
  export STOP_BY_CODE=1

  if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    docker stop "$CONTAINER_NAME" 2>/dev/null
    docker rm "$CONTAINER_NAME" 2>/dev/null
  elif current_os_is_windows; then
    cmd.exe /C "docker stop $CONTAINER_NAME"
    cmd.exe /C "docker rm $CONTAINER_NAME"
  fi
}

trap cleanup EXIT SIGINT SIGTERM SIGHUP SIGQUIT

docker run --rm -it --init --gpus all --name $CONTAINER_NAME \
  -v "$DOWNLOAD_MODELS_PY_PATH:/root/FramePack/download_models.py" \
  -v "${CURRENT_APP_PATH}/hf_download:/root/FramePack/hf_download" \
  $HF_ENDPOINT_PARAM -e HF_HOME="/root/FramePack/hf_download" \
  "$APP_IMAGE_REPO" python /root/FramePack/download_models.py

exit_code=$?

if [ $exit_code -ne 0 ]; then
   echo $exit_code
    if [ $STOP_BY_CODE -ne 1 ]; then
      # echo "lmdevent:docker_run_error"
      echo "docker_run_error"
    fi
   exit 1
fi

echo "lmdprogress:100"


